package org.xtense.model.actions;

import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import org.xtense.engine.IConstants;

public class RequestForSizeAction implements IUserAction {
	private String documentID;
	private int elementPre;
	private int size;

	public RequestForSizeAction(String documentID, int elementPre, int size) {
		this.documentID = documentID;
		this.elementPre = elementPre;
		this.size = size;
	}
	
	public void removeOneAdded() {
		size--;
	}

	@Override
	public List<String> generateSql() {
		String docIdExpr = MessageFormat.format(IConstants.Sql_Int_Equal,
				new Object[] { IConstants.Document_ID, documentID });
		String elePreExpr = MessageFormat.format(IConstants.Sql_Greater_Than,
				new Object[] { IConstants.Element_Pre, elementPre });
		String andExpr = MessageFormat.format(IConstants.Sql_And, new Object[] {
				elePreExpr, docIdExpr });

		String elePreIncrExpr = IConstants.Element_Pre + " = "
				+ IConstants.Element_Pre + " + " + size;

		// First update elementPre in Attribute table, Element table and Text
		// table.
		List<String> sql = new ArrayList<String>();
		Iterator<String> iterator;
		for (iterator = IConstants.AETPtables.values().iterator(); iterator
				.hasNext();) {
			sql.add(MessageFormat.format(IConstants.Sql_Update, new Object[] {
					iterator.next(), elePreIncrExpr, andExpr }));
		}

		// Second, update elementPre in path table.
		sql.add(MessageFormat.format(IConstants.Sql_Update, new Object[] {
				IConstants.Path_Table, elePreIncrExpr, andExpr }));

		// Third, update parentPre in Element table.
		String parPreIncrExpr = IConstants.Parent_Pre + " = "
				+ IConstants.Parent_Pre + " + " + size;
		String parPreGTExpr = MessageFormat.format(IConstants.Sql_Greater_Than,
				new Object[] { IConstants.Parent_Pre, elementPre });
		andExpr = MessageFormat.format(IConstants.Sql_And, new Object[] {
				parPreGTExpr, docIdExpr });
		sql.add(MessageFormat.format(IConstants.Sql_Update, new Object[] {
				IConstants.Element_Table, parPreIncrExpr, andExpr }));
		return sql;
	}

}
